package com.lmx.cloud;


import com.lmx.bean.FileUnit;
import com.lmx.control.WlanManager;
import com.lmx.creceive.receive;
import com.lmx.util.LogUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NoRouteToHostException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.glassfish.grizzly.threadpool.FixedThreadPool;

// 文件上传的队列，作用是自动从文件夹获取文件，然后上传，上传成功即删除，它的上传是通过调用FileUploader实现的
public class FileUploadQueue {
    private static Queue<int[]>queue;
    private static final HashSet<FileUnit> files = new HashSet<>();
    private static final AtomicBoolean enableUpload = new AtomicBoolean(true);
    private static final AtomicBoolean tooManyFilesFlag = new AtomicBoolean(false);
    //max to 6GB
    private static final long MaxStorageSize = 6442450944L;
    private static final AtomicLong fileStorage = new AtomicLong(0);
    
    //传文件，加到上传列表
    //path = 日期+topic+文件名
//    public static void add(File file, String path, String topic) {
//        add(file, WlanManager.device_name, path, topic);
//    }
//
//    public static void add(File file, String mac, String path, String topic) {
//        if (!file.exists())
//            return;
//        files.offer(new FileUnit(file, topic));
//        if (fileStorage.addAndGet(file.length()) > MaxStorageSize && tooManyFilesFlag.compareAndSet(false, true)) {
//            LogUtil.log_error("[-] Too many files to upload, cover old file.");
//            while (fileStorage.get() > (MaxStorageSize - MaxStorageSize / 4)) {
//                fileStorage.addAndGet(-Objects.requireNonNull(files.peek()).getFile().length());
//                Objects.requireNonNull(files.poll()).getFile().delete();
//            }
//            tooManyFilesFlag.set(false);
//        }
//    }


    public static HashSet<FileUnit> getFiles() {
        return files;
    }

    public static void addAllByPath(String path) {
            File[] fileNames = new File(path).listFiles();
            if (fileNames == null)
                return;
            for (File file : fileNames) {
                if(file.isDirectory())
                    continue;
                fileStorage.addAndGet(file.length());
                String fileName = file.getName();
                String[] components = fileName.split("_", 2);
                if (components.length != 2) {
                    System.out.println("发现格式异常的非法文件:" + fileName);
                    return;
                }
                String deviceName = components[0];
                String dataFileName = components[1];
                LocalDate date = LocalDate.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                files.add(new FileUnit(file, "distributed/" + date.format(formatter) + "/"
                        + deviceName + "/" + dataFileName, deviceName));
            }
            System.out.println("[+] All file add to upload queue @" + path);
    }

    public static void start() throws IOException {
        // int index=0;
        // queue=new ConcurrentLinkedDeque<>();
        // Thread thread=new Thread(new Runnable() {

        //     @Override
        //     public void run() {
        //         // TODO Auto-generated method stub
        //         try {
        //             FileUploader.upload(queue);
        //         } catch (Exception e) {
        //             // TODO Auto-generated catch block
        //             e.printStackTrace();
        //         }
        //     }
            
        // });
        // thread.setDaemon(true);
        // thread.start();
        
        // receive myReceive=new receive();
        FileUploader.InitUpload();
        while(true)
        {   
            try{
                // if(queue.size()<=100)
                // {
                    System.out.println("java start");
                    // int[] x={1,2,3,20,5,6,7,8,9,10,11,12,25};
                    // FileUploader.upload(x);
                    FileUploader.upload(new receive().canreceive());
                // }
                    // try{
                    // Thread.sleep(200);
                    // }catch(InterruptedException e){
                    //     e.printStackTrace();
                    // }
                // int t[]=new int[8];
                // for(int i=0;i<8;++i)
                //     t[i]=i;
                // queue.offer(t);  
                // System.out.println(queue.size());
            }catch(Exception e){
                // System.out.println("队列满："+queue.size());
                e.printStackTrace();
            }
        }
        // Runtime是用来执行命令行的
        /*Runtime run = Runtime.getRuntime();
        Process ps = null;
        
        try {
            System.out.println("Removing: data...");
            ps = run.exec(new String[]{"/bin/sh", "-c", "rm -rf /home/hit-ices/data_all"});
            Thread.sleep(1000);
            System.out.println("Making dir: data...");
            ps = run.exec(new String[]{"/bin/sh", "-c", "mkdir /home/hit-ices/data_all"});
            ps = run.exec(new String[]{"/bin/sh", "-c", "mkdir /home/hit-ices/data_all/depth"});
            ps = run.exec(new String[]{"/bin/sh", "-c", "mkdir /home/hit-ices/data_all/color"});
            Thread.sleep(1000);
            //ps = run.exec(new String[]{"python", "/home/pi/laser_switch/main.py"});
            //Thread.sleep(2000);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }*/
        // System.out.println("[+] File upload start");

        // // 设置上传标志位，开始上传
        // enableUpload.set(true);
        // ThreadFlag.set(true);
        // if (uploadThread == null || !uploadThread.isAlive()) {
        //     // 创建新线程用来上传，线程函数是UploadFile
        //     uploadThread = new Thread(FileUploadQueue::UploadFile);
        //     uploadThread.setName("upload");
        //     uploadThread.start();
        // }


    }

    public static void pause() {
        enableUpload.set(false);
    }

    public static void resume() {
        enableUpload.set(true);
    }

    public static void stop() {

        enableUpload.set(false);
        ThreadFlag.set(false);
    }

    

    private static String storageSize(long size) {
        if (size < 1024) {
            return size + "B";
        } else if (size < 1024 * 1024) {
            return size / 1024L + "KB";
        } else if (size < 1073741824L) {
            return size / 1048576L + "MB";
        } else
            return size / 1073741824L + "GB";
    }

    private static final AtomicBoolean ThreadFlag = new AtomicBoolean(true);
    private static Thread uploadThread;
}